﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections.Specialized;
using MVCPets.Helpers;

namespace MVCPets.Extensions
{
  public static class DictionaryExtensions
  {
    #region Public Methods
    /// <summary>
    /// Attempts to pull a strongly typed value from the IDictionary.
    /// If it is not found or the conversion fails then it returns the
    /// last parameter.
    /// </summary>
    /// <typeparam name="T">The type of the item</typeparam>
    /// <param name="data">The IDictionary object</param>
    /// <param name="param">The key</param>
    /// <param name="defaultValue">The default value to return</param>
    /// <returns>The converted type or the default value</returns>
    public static T GetItem<T>(this IDictionary<string, object> data, string param, T defaultValue)
    {
      if (data.ContainsKey(param))
        return ConversionHelpers.ConvertItem<T>(data[param] as object, defaultValue);
      else
        return defaultValue;
    }

    /// <summary>
    /// Attempts to pull a strongly typed value from the IDictionary.
    /// If it is not found or the conversion fails then it returns the
    /// last parameter.
    /// </summary>
    /// <typeparam name="T">The type of the item</typeparam>
    /// <param name="data">The IDictionary object</param>
    /// <param name="param">The key</param>
    /// <param name="defaultValue">The default value to return</param>
    /// <returns>The converted type or the default value</returns>
    public static T GetItem<T>(this IDictionary<string, string> data, string param, T defaultValue)
    {
      if (data.ContainsKey(param))
        return ConversionHelpers.ConvertItem<T>(data[param] as object, defaultValue);
      else
        return defaultValue;
    }

    /// <summary>
    /// Attempts to pull a strongly typed value from the NameValueCollection.
    /// If it is not found or the conversion fails then it returns the
    /// last parameter.
    /// </summary>
    /// <typeparam name="T">The type of the item</typeparam>
    /// <param name="data">The NameValueCollection object</param>
    /// <param name="param">The key</param>
    /// <param name="defaultValue">The default value to return</param>
    /// <returns>The converted type or the default value</returns>
    public static T GetItem<T>(this NameValueCollection data, string param, T defaultValue)
    {
      if (data.AllKeys.Contains(param))
        return ConversionHelpers.ConvertItem<T>(data[param] as object, defaultValue);
      else
        return defaultValue;
    }

    public static double? ParseDouble(this IDictionary<string, string> data, string key)
    {
      double? toReturn = null;

      if (data.ContainsKey(key)) toReturn = data[key].Parse<double?>();

      return toReturn;
    }
    #endregion
  }
}